<template>
  <div>
    <!-- 页面标题区域 -->
    <section class="py-8 mb-8 relative overflow-hidden">
      <div class="container max-w-7xl mx-auto px-4">
        <h1 class="text-4xl font-bold tracking-tight mb-4 troublemaker-title">职场搅屎棍排行榜</h1>
        <p class="text-gray-600 dark:text-gray-400 max-w-3xl troublemaker-description">
          这里列出了各种常见的职场搅屎棍类型及其特征，帮助你识别并远离这些有毒的职场人物。所有内容均为模拟数据，如有雷同纯属巧合。
        </p>
      </div>
      <!-- 背景装饰 -->
      <div
        class="absolute top-0 right-0 w-32 h-32 bg-secondary-100 dark:bg-secondary-900 rounded-full opacity-20 decoration-bubble">
      </div>
      <div
        class="absolute bottom-0 left-0 w-40 h-40 bg-primary-100 dark:bg-primary-900 rounded-full opacity-20 decoration-bubble">
      </div>
    </section>

    <!-- 筛选器 -->
    <div
      class="bg-white dark:bg-gray-950 rounded-lg shadow-sm border border-gray-200 dark:border-gray-800 p-6 mb-8 filter-container max-w-7xl mx-auto transition-all duration-300 hover:shadow-md">
      <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div>
          <label for="skill" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">特殊技能</label>
          <Select v-model="selectedSkill">
            <SelectTrigger class="w-full">
              <SelectValue placeholder="选择特殊技能" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="">全部技能</SelectItem>
              <SelectItem v-for="skill in allSkills" :key="skill" :value="skill">{{ skill }}</SelectItem>
            </SelectContent>
          </Select>
        </div>
        <div>
          <label for="sort" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">排序方式</label>
          <Select v-model="sortOption">
            <SelectTrigger class="w-full">
              <SelectValue placeholder="选择排序方式" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="rank">按危害排名</SelectItem>
              <SelectItem value="name">按姓名</SelectItem>
            </SelectContent>
          </Select>
        </div>
        <div>
          <label for="search" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">搜索</label>
          <div class="relative">
            <Input v-model="searchQuery" type="text" placeholder="搜索名称或描述..." />
            <div class="absolute inset-y-0 right-0 flex items-center pr-3">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-gray-400" fill="none" viewBox="0 0 24 24"
                stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                  d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
              </svg>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 排行榜 -->
    <div class="max-w-7xl mx-auto px-4">
      <div class="grid grid-cols-1 gap-8">
        <div v-for="(troublemaker, index) in filteredTroublemakers" :key="troublemaker.id"
          class="transform hover:-translate-y-1 transition-all duration-300 troublemaker-card" :data-index="index">
          <Card class="overflow-hidden hover:shadow-lg">
            <CardContent class="p-6">
              <div class="flex flex-col md:flex-row">
                <div class="flex-shrink-0 mb-4 md:mb-0 md:mr-6">
                  <div
                    class="w-20 h-20 bg-primary-100 dark:bg-primary-900 rounded-full flex items-center justify-center text-2xl font-bold text-primary-600 dark:text-primary-400 rank-icon">
                    #{{ troublemaker.rank }}
                  </div>
                </div>
                <div class="flex-1">
                  <div class="flex flex-col md:flex-row md:items-center justify-between mb-4">
                    <CardTitle class="text-xl mb-2 md:mb-0">{{ troublemaker.name }}</CardTitle>
                    <div class="hidden md:block">
                      <NuxtLink :to="`/troublemakers/${troublemaker.id}`"
                        class="transform hover:scale-105 transition-transform">
                        <Button variant="outline" size="sm">查看详情</Button>
                      </NuxtLink>
                    </div>
                  </div>
                  <div class="flex flex-wrap gap-2 mb-4">
                    <Badge v-for="skill in troublemaker.skills" :key="skill" variant="secondary"
                      class="transform hover:scale-105 transition-transform">
                      {{ skill }}
                    </Badge>
                  </div>
                  <div class="mb-4">
                    <div class="mb-2 flex items-center justify-between">
                      <span class="text-sm font-medium text-gray-700 dark:text-gray-300">危害指数</span>
                      <span class="text-sm font-medium text-gray-700 dark:text-gray-300">{{ troublemaker.harmScore
                        }}/10</span>
                    </div>
                    <div class="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2.5 overflow-hidden">
                      <div class="h-2.5 rounded-full progress-bar" :style="`width: ${troublemaker.harmScore * 10}%`"
                        :class="getHarmScoreClass(troublemaker.harmScore)"></div>
                    </div>
                  </div>
                  <p class="text-gray-600 dark:text-gray-400 mb-6">
                    {{ troublemaker.description }}
                  </p>
                  <div class="mb-6">
                    <h3 class="text-sm font-semibold mb-2">常见行为特征:</h3>
                    <ul class="list-disc pl-5 space-y-1.5 text-sm text-gray-600 dark:text-gray-400">
                      <li v-for="(behavior, behIndex) in troublemaker.behaviors" :key="behIndex" class="behavior-anim"
                        :style="`--delay: ${behIndex * 0.1}s`">
                        {{ behavior }}
                      </li>
                    </ul>
                  </div>
                  <div class="md:hidden">
                    <NuxtLink :to="`/troublemakers/${troublemaker.id}`" class="w-full">
                      <Button variant="outline" class="w-full">查看详情</Button>
                    </NuxtLink>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>

      <!-- 分页 -->
      <div class="mt-10 flex justify-center">
        <nav class="flex items-center space-x-2">
          <Button variant="outline" :disabled="currentPage === 1" @click="currentPage--">
            上一页
          </Button>
          <Button v-for="page in totalPages" :key="page" :variant="currentPage === page ? 'default' : 'outline'"
            @click="currentPage = page">
            {{ page }}
          </Button>
          <Button variant="outline" :disabled="currentPage === totalPages" @click="currentPage++">
            下一页
          </Button>
        </nav>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue';
import { useNuxtApp } from '#app';
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardTitle } from '@/components/ui/card'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select'

// 获取GSAP实例
const { $gsap } = useNuxtApp();

// 筛选和排序状态
const searchQuery = ref('');
const sortOption = ref('rank');
const selectedSkill = ref('');
const currentPage = ref(1);
const itemsPerPage = 5;

// 模拟数据
const troublemakers = [
  {
    id: '1',
    name: '变脸禽经理',
    rank: 1,
    skills: ['职场PUA', '画饼', '窃取功劳'],
    harmScore: 9.5,
    description: '该经理在员工面前永远一副和蔼可亲的面孔，但在上级面前会把所有功劳归于自己，所有错误推给团队成员。擅长通过贬低员工自信心来控制团队。',
    behaviors: [
      '从不记录自己的承诺和任务，便于后期否认',
      '夸大自己的贡献，淡化团队其他成员的努力',
      '在上级面前贬低团队成员，营造"只有我能救场"的假象',
      '精通管理上级对自己的印象，对下对上两张脸'
    ]
  },
  {
    id: '2',
    name: '办公室政治家',
    rank: 2,
    skills: ['拉帮结派', '散播谣言', '制造矛盾'],
    harmScore: 9.2,
    description: '这位"政治家"擅长在同事之间制造矛盾，通过散播谣言和半真半假的信息来破坏团队关系，最终达到自己上位的目的。',
    behaviors: [
      '经常组织"小圈子"的私下活动，排除特定同事',
      '利用午餐、茶歇等非正式场合散布对特定同事的负面评价',
      '擅长在背后质疑他人能力和工作态度，但面对面时却表现友好',
      '通过控制信息流动来操纵团队成员之间的关系'
    ]
  },
  {
    id: '3',
    name: '甩锅艺术家',
    rank: 3,
    skills: ['责任推卸', '表面工作', '危机公关'],
    harmScore: 8.7,
    description: '无论什么项目出了问题，总能找到完美的理由将责任推给他人。同时，擅长在上级面前表现得非常努力，实际上几乎不做实质性工作。',
    behaviors: [
      '擅长模糊表达，不留下明确责任记录',
      '经常抢先向领导汇报进展，但具体问题"不在自己职责范围"',
      '有意拖延或隐瞒潜在风险，等问题爆发后再甩锅',
      '对失败项目迅速撇清关系，对成功项目则表现积极参与'
    ]
  },
  {
    id: '4',
    name: '信息垄断者',
    rank: 4,
    skills: ['信息控制', '权力寻租', '排挤新人'],
    harmScore: 8.5,
    description: '通过垄断关键信息和资源，使得团队其他成员必须依赖自己。对新人采取不教、乱教或者错教的方式，防止自己的"地位"被撼动。',
    behaviors: [
      '不愿文档化自己的工作流程和知识点',
      '故意使用复杂晦涩的术语和非标准方法',
      '在团队成员需要协助时故意隐瞒关键信息',
      '对提高工作透明度的建议表现出消极抵抗'
    ]
  },
  {
    id: '5',
    name: '表面功夫大师',
    rank: 5,
    skills: ['数据造假', '形式主义', '邀功请赏'],
    description: '做事只求表面功夫，不求实际效果。擅长包装数据和成果，让领导看到"漂亮"的结果，实际工作却一团糟。',
    harmScore: 8.2,
    behaviors: [
      '在重要会议前突击准备表面工作，会后则完全放置',
      '擅长制作华丽的PPT和报表，掩盖实质问题',
      '技巧性地选择对自己有利的数据进行汇报和展示',
      '在领导关注点明确后，迅速转变工作重心以迎合'
    ]
  },
  {
    id: '6',
    name: '资源独占者',
    rank: 6,
    skills: ['资源霸占', '权力博弈', '团队破坏'],
    harmScore: 7.9,
    description: '总是试图控制和独占团队资源，包括预算、人员和项目机会。通过垄断资源来巩固自己的"不可替代性"，使其他人难以正常工作。',
    behaviors: [
      '过度申请预算和人力，远超实际需要',
      '强行介入其他团队项目，扩大自己的"势力范围"',
      '将资源分配权视为自己的私人权力，任意决定谁能获得支持',
      '阻挠对资源分配流程的规范化和透明化'
    ]
  },
  {
    id: '7',
    name: '情绪操控大师',
    rank: 7,
    skills: ['情绪爆发', '道德绑架', '受害者心态'],
    harmScore: 7.6,
    description: '利用情绪爆发和受害者心态来控制团队气氛，让同事和领导小心翼翼地避免触怒自己。通过"道德绑架"方式获取特殊待遇。',
    behaviors: [
      '在关键时刻情绪爆发，迫使他人让步',
      '过度强调自己的付出和"牺牲"，暗示团队欠自己的',
      '频繁表示自己被冒犯或不被尊重，但标准模糊且不一致',
      '利用团队和谐氛围，让同事不得不迁就自己的情绪需求'
    ]
  },
  {
    id: '8',
    name: '能力造假者',
    rank: 8,
    skills: ['简历造假', '外行忽悠', '推卸责任'],
    harmScore: 7.5,
    description: '凭借出色的口才和包装能力获得职位，但实际专业能力严重不足。当面临实际工作挑战时，会通过各种方式逃避或转嫁责任。',
    behaviors: [
      '使用大量行业术语和流行概念，但缺乏实质内容',
      '总是强调"战略层面"和"大局观"，回避具体执行问题',
      '将自己的错误和能力不足归咎于工具、环境或他人',
      '不断寻找新的热点领域跳槽，避免在一个领域被深度验证'
    ]
  }
];

// 获取所有技能列表（用于筛选）
const allSkills = computed(() => {
  const skillSet = new Set<string>();
  troublemakers.forEach(item => {
    item.skills.forEach(skill => skillSet.add(skill));
  });
  return Array.from(skillSet).sort();
});

// 过滤和排序数据
const filteredTroublemakers = computed(() => {
  let result = [...troublemakers];

  // 应用技能筛选
  if (selectedSkill.value) {
    result = result.filter(item => item.skills.includes(selectedSkill.value));
  }

  // 应用搜索
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(item =>
      item.name.toLowerCase().includes(query) ||
      item.description.toLowerCase().includes(query) ||
      item.skills.some(skill => skill.toLowerCase().includes(query)) ||
      item.behaviors.some(behavior => behavior.toLowerCase().includes(query))
    );
  }

  // 应用排序
  if (sortOption.value === 'name') {
    result.sort((a, b) => a.name.localeCompare(b.name));
  } else {
    // 默认按职场危害排序
    result.sort((a, b) => a.rank - b.rank);
  }

  // 分页
  const startIndex = (currentPage.value - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  return result.slice(startIndex, endIndex);
});

// 计算总页数
const totalPages = computed(() => {
  let filteredTotal = troublemakers.length;

  if (selectedSkill.value) {
    filteredTotal = troublemakers.filter(item => item.skills.includes(selectedSkill.value)).length;
  }

  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    filteredTotal = troublemakers.filter(item =>
      item.name.toLowerCase().includes(query) ||
      item.description.toLowerCase().includes(query) ||
      item.skills.some(skill => skill.toLowerCase().includes(query)) ||
      item.behaviors.some(behavior => behavior.toLowerCase().includes(query))
    ).length;
  }

  return Math.ceil(filteredTotal / itemsPerPage);
});

// 获取危害指数对应的样式类
const getHarmScoreClass = (score: number) => {
  if (score >= 9) return 'bg-red-500 dark:bg-red-600';
  if (score >= 8) return 'bg-orange-500 dark:bg-orange-600';
  if (score >= 7) return 'bg-yellow-500 dark:bg-yellow-600';
  if (score >= 6) return 'bg-blue-500 dark:bg-blue-600';
  return 'bg-green-500 dark:bg-green-600';
};

// 监听筛选条件变化，重置到第一页
watch([selectedSkill, searchQuery], () => {
  currentPage.value = 1;
});

// 使用GSAP添加动画效果
onMounted(() => {
  try {
    // 先确保元素可见（以防GSAP出错）
    document.querySelectorAll('.troublemaker-title, .troublemaker-description, .filter-container, .troublemaker-card, .rank-icon')
      .forEach(el => {
        (el as HTMLElement).style.opacity = '1';
      });

    // 标题和描述动画
    if ($gsap) {
      $gsap.from('.troublemaker-title', {
        opacity: 0,
        y: 20,
        duration: 0.8,
        ease: 'power2.out'
      });

      $gsap.from('.troublemaker-description', {
        opacity: 0,
        y: 20,
        duration: 0.8,
        delay: 0.2,
        ease: 'power2.out'
      });

      // 筛选器动画
      $gsap.from('.filter-container', {
        opacity: 0,
        y: 20,
        duration: 0.8,
        delay: 0.4,
        ease: 'power2.out'
      });

      // 卡片动画
      $gsap.from('.troublemaker-card', {
        opacity: 0,
        y: 40,
        duration: 0.8,
        stagger: 0.15, // 每个卡片依次显示
        delay: 0.6,
        ease: 'power2.out'
      });

      // 排名图标动画
      $gsap.from('.rank-icon', {
        scale: 0.5,
        opacity: 0,
        rotation: -10,
        duration: 0.8,
        stagger: 0.15,
        delay: 0.7,
        ease: 'elastic.out(1, 0.5)'
      });

      // 进度条动画
      $gsap.to('.progress-bar', {
        width: (i, el) => el.getAttribute('style')?.replace('width: ', '').replace(';', '') || '0%',
        duration: 1.2,
        stagger: 0.15,
        delay: 0.8,
        ease: 'power2.out'
      });

      // 背景装饰动画
      $gsap.to('.decoration-bubble', {
        x: i => (Math.random() * 30 - 15),
        y: i => (Math.random() * 30 - 15),
        scale: i => (Math.random() * 0.2 + 0.9),
        duration: 4,
        repeat: -1,
        yoyo: true,
        ease: 'power1.inOut'
      });
    }
  } catch (error) {
    console.error('动画加载失败', error);
    // 确保元素可见（出错时的备用方案）
    document.querySelectorAll('.troublemaker-title, .troublemaker-description, .filter-container, .troublemaker-card, .rank-icon')
      .forEach(el => {
        (el as HTMLElement).style.opacity = '1';
      });
  }
});
</script>

<style scoped>
/* 删除opacity: 0设置，确保元素默认可见 */
/* 
.troublemaker-title,
.troublemaker-description,
.filter-container,
.troublemaker-card,
.rank-icon {
  opacity: 0;
}
*/

.behavior-anim {
  /* opacity: 0; */
  animation: fadeIn 0.8s forwards;
  animation-delay: calc(800ms + var(--delay));
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

.progress-bar {
  width: 0;
}
</style>